/*
 * Copyright 2011 J. Auer, J. Andert, F.-J. Jendrusch, U. Celebi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.fuberlin.replication.application.android.communication.wifi;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import de.fuberlin.replication.application.android.communication.CommunicationHelperAbstract;
import de.fuberlin.replication.communication.CommunicationAlreadyEstablishedException;
import de.fuberlin.replication.communication.wifi.android.AndroidWiFiCommunication;

/**
 * Android-specific WiFi communication helper.
 */
public class WiFiCommunicationHelper extends CommunicationHelperAbstract {
	/** Enable WiFi request code. */
	public static final int REQUEST_ENABLE_WIFI = 1;

	/** Enter host request code. */
	private static final int REQUEST_ENTER_HOST = 2;

	/** WiFi communication. */
	AndroidWiFiCommunication communication;

	/**
	 * @see CommunicationHelperAbstract#CommunicationHelperAbstract()
	 */
	public WiFiCommunicationHelper() {
		super();
	}

	@Override
	public AndroidWiFiCommunication getCommunication() {
		if (communication == null)
			throw new IllegalStateException("Synchronization not yet started");

		return communication;
	}

	@Override
	protected void listen() throws IOException {
		communication.listen(getActivity().getBaseContext());
	}

	@Override
	protected void connect() {
		Intent intent = new Intent(getActivity(), WiFiEnterHostActivity.class);
		getActivity().startActivityForResult(intent, REQUEST_ENTER_HOST);
	}

	@Override
	protected void waitEstablished() throws InterruptedException {
		communication.waitEstablished(0);
	}

	@Override
	protected void close() {
		if (communication != null)
			communication.close();
	}

	@Override
	public void onSynchronizationStart() {
		communication = new AndroidWiFiCommunication();

		/**
		 * Check WiFi state: <code>
		int state = ((WifiManager) getActivity().getBaseContext().getSystemService(Context.WIFI_SERVICE)).getWifiState();
		 * </code> Using WiFi as local hotspot will return <code>state == WIFI_STATE_DISABLED</code>,
		 * therefore it's not recommended to force enabled-state here.
		 */

		super.onSynchronizationStart();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case REQUEST_ENABLE_WIFI:
				// Handle WiFi enable request.

				break;
			case REQUEST_ENTER_HOST:
				if (resultCode == Activity.RESULT_OK) {
					ConnectTask task = new WiFiConnectTask();
					task.execute(data.getExtras().getString(WiFiEnterHostActivity.EXTRA_HOST));
				} else
					getUIHandler().obtainMessage(UICallback.MESSAGE_DIALOG_SHOW, DIALOG_INITIALIZING, 0).sendToTarget();

				break;
			default:
				super.onActivityResult(requestCode, resultCode, data);

				break;
		}
	}

	private class WiFiConnectTask extends ConnectTask {
		public WiFiConnectTask() {
			super();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			boolean result = false;

			try {
				communication.connect(params[0], getActivity().getBaseContext());

				result = true;
			} catch (CommunicationAlreadyEstablishedException e) {
			}

			return Boolean.valueOf(result);
		}
	}
}